<?php

class DataTables
{

  /**
   * Constructor
   */
  public function  __construct() {}

  public function execute(sfWebRequest $request, Doctrine_Table $table_class, $lucene_indexes = null) {
    return $this->exec($request, $table_class, Doctrine_Core::HYDRATE_ARRAY, $lucene_indexes);
  }

  public function executeFetchObject(sfWebRequest $request, Doctrine_Table $table_class, $lucene_indexes = null) {
    return $this->exec($request, $table_class,Doctrine_Core::HYDRATE_RECORD,  $lucene_indexes);
  }

  private function exec(sfWebRequest $request, Doctrine_Table $table_class, $hydration_mode = Doctrine_Core::HYDRATE_RECORD,$lucene_indexes = null) {
      $fields = $table_class->getFields();
      // set limit
      $limit = ($request->getParameter('iDisplayLength')) ? $request->getParameter('iDisplayLength') : 10;
      // set current page
      $page = ($request->getParameter('iDisplayStart')/$limit) +1;
      // set column to sort
      if($request->getParameter('iSortCol_0') > max(array_keys($fields)) || $request->getParameter('iSortCol_0') <= 0 || $request->getParameter('iSortCol_0') == '') {
          $sorder = $table_class->getDefaultOrder();
          // set sort direction
          $sort = $table_class->getDefaultDirection();
      } else {
          // set sort direction
          $sorder = $fields[$request->getParameter('iSortCol_0')];
          $sort = ($request->getParameter('sSortDir_0')) ? $request->getParameter('sSortDir_0') : 'DESC';
      }

      $order = $sorder.' '.$sort;

      $param = ($request->getParameter('param')) ? $request->getParameter('param') : null;

      // fetch data based on index
      if ($lucene_indexes) {
          $query = $table_class->selectQuery()
                        ->whereIn($table_class->getPk(), $lucene_indexes);
          if (isset($param))
          {
            foreach ($param as $key=>$value)
            {
              $query->andWhere("$key = ?",  urldecode($value));
            }
          }
          $query->orderBy($order);
      } else {
          $query = $table_class->selectQuery();
          if (isset($param))
          {
            $count = 0;
            foreach ($param as $key=>$value)
            {


              if(strpos($key, 'greater_than_or_equal_to_') > 0) {
                $query->andWhere(str_replace('_greater_than_or_equal_to_', '', $key).' >= ?',urldecode($value));
              }
              else if(strpos($key, 'less_than_or_equal_to_') > 0) {
                $query->andWhere(str_replace('_less_than_or_equal_to_', '', $key).' <= ?',urldecode($value));
              }
              else {
                $query->andWhere("$key LIKE ?",  '%'.urldecode($value).'%');
              }
              $count++;
            }



          }
          $query->orderBy($order);
      }

    $pager = new Doctrine_Pager($query,$page,$limit);
    $data = $pager->execute(array(), $hydration_mode );
    return compact('pager','data');
  }

  private function original_exec(sfWebRequest $request, Doctrine_Table $table_class, $hydration_mode = Doctrine_Core::HYDRATE_RECORD,$lucene_indexes = null) {
      $fields = $table_class->getFields();
      // set limit
      $limit = ($request->getParameter('iDisplayLength')) ? $request->getParameter('iDisplayLength') : 10;
      // set current page
      $page = ($request->getParameter('iDisplayStart')/$limit) +1;
      // set column to sort
      if($request->getParameter('iSortCol_0') > max(array_keys($fields)) || $request->getParameter('iSortCol_0') <= 0 || $request->getParameter('iSortCol_0') == '') {
          $sorder = $table_class->getDefaultOrder();
          // set sort direction
          $sort = $table_class->getDefaultDirection();
      } else {
          // set sort direction
          $sorder = $fields[$request->getParameter('iSortCol_0')];
          $sort = ($request->getParameter('sSortDir_0')) ? $request->getParameter('sSortDir_0') : 'DESC';
      }

      $order = $sorder.' '.$sort;

      $param = ($request->getParameter('param')) ? $request->getParameter('param') : null;

      // fetch data based on index
      if ($lucene_indexes) {
          $query = $table_class->selectQuery()
                        ->whereIn($table_class->getPk(), $lucene_indexes);
          if (isset($param))
          {
            foreach ($param as $key=>$value)
            {
              $query->andWhere("$key = ?",  urldecode($value));
            }
          }
          $query->orderBy($order);
      } else {
          $query = $table_class->selectQuery();
          if (isset($param))
          {
            $count = 0;
            foreach ($param as $key=>$value)
            {
              if($count > 0) {
                $query->andWhere("$key = ?",  urldecode($value));
              } else {
                $query->andWhere("$key = ?",urldecode($value));
              }
              $count++;
            }
          }
          $query->orderBy($order);
      }

    $pager = new Doctrine_Pager($query,$page,$limit);
    $data = $pager->execute(array(), $hydration_mode );
    return compact('pager','data');
  }

  public static function renderAOColumns($cols) {
    $columns = null;
    foreach($cols as $col) {
      if (!$col['bVisible']) {
        if($columns) {
          $columns .= ', {"bVisible":0}';
        } else {
          $columns .= '{"bVisible":0}';
        }
      } else {
        if($columns) {
          $columns .= ', { "sWidth": "'.$col['sWidth'].'"}';
        } else {
          $columns .= '{ "sWidth": "'.$col['sWidth'].'"}';
        }
      }
    }
    return '['.$columns.']';
  }
}

?>
